/****************************************************************
*PWM Code for Atmel Mega AVR
*Copyright (C) 2007 Justin Richards <ratmandu@gmail.com> OR <justin.richards@ratmandu.net>
*
*This program is free software; you can redistribute it and/or
*modify it under the terms of the GNU General Public License
*as published by the Free Software Foundation; either version 2
*of the License, or (at your option) any later version.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program; if not, write to the 
*Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*
*****************************************************************/


#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/sleep.h>
#include <inttypes.h>

// This will start the 8 Bit Timer/Counter 1 in Mode 1, Phase correct PWM with no prescaling

void initPWM(void) {
	// set pwm ports to output.
	DDRB = (1 << PB3) | (1 << PB4);
	
	// Set counter initial value
	TCNT0 = 0x00;
	
	// Set Output Compare register initial values.
	OCR0A = 0xFF;
	OCR0B = 0xFF;
	
	// Start timer Phase Correct PWM. No prescaling
	TCCR0A = (1<<COM0A0) | (1<<COM0A1) | (1<<COM0B0) | (1<<COM0B1) | (1<<WGM00);
	TCCR0B = (1<<FOC0A) | (1<<FOC0B) | (1<<CS00);
	
}

int main (void) {
	// run the function to initialize the PWM stuff
    initPWM();
	
	// lets init a variable for our counter
	int i = 255;
	
	// start the big, endless loop.
	while(1) {
		
	
		// now, lets put in some code to ramp the pwm up, then down.
		// 255 = 0xFF = Off
		// 150 = 0x64 = plenty bright for the LEDs I am using.
		while (i < 255) {
			OCR0A = i;
			OCR0B = i;
			i = i+1;
			_delay_ms(20);
		}
		
		while (i > 150) {
			OCR0A = i;
			OCR0B = i;
			i = i-1;
			_delay_ms(20);
		}
	}
	
	return 0;
}
